package com.zhangyj.impl.actions;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhangyj.action.AbstractAction;
import com.zhangyj.action.RequestAction;
import com.zhangyj.action.RequestMethod;
import com.zhangyj.action.ResponseResultType;
import com.zhangyj.util.IOTools;
@RequestAction(name="attach")
public class AttachmentAction extends AbstractAction {
	Logger log = LoggerFactory.getLogger(AttachmentAction.class);
	private static final long serialVersionUID = -1525488071835340550L;

	@RequestMethod(name = "upload", result = ResponseResultType.JSON)
	public String upload() throws Exception {
		try {
			String filename = request.getHeader("X-File-Name");
			if (filename == null) {
				filename = upload1();
			} else {
				InputStream is = null;
				FileOutputStream fos = null;
				try {
					filename = URLDecoder.decode(filename, "UTF-8");
					is = request.getInputStream();
					String realPath = context.getRealPath("uploadfiles") + "/";
					fos = new FileOutputStream(new File(realPath + filename));
					IOTools.copy(is, fos);
				} finally {
					try {
						fos.close();
						is.close();
					} catch (IOException ignored) {
					}
				}
			}
			response.setStatus(HttpServletResponse.SC_OK);
			return "{success: true}";
		} catch (FileNotFoundException ex) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			log.error("has thrown an exception: " + ex.getMessage());
			return "{success: false}";
		} catch (Exception ex) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			log.error("has thrown an exception: " + ex.getMessage());
			return "{success: false}";
		}
	}

	private String upload1() throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		List<?> items = upload.parseRequest(request);
		if (items == null || items.size() == 0) {
			return null;
		}
		FileItem item = (FileItem) items.get(0);
		String filename = item.getName();
		int index = filename.lastIndexOf("/");
		if (index == -1)
			index = filename.lastIndexOf("\\");
		if (index != -1) {
			filename = filename.substring(index + 1);
		}
		String realPath = context.getRealPath("uploadfiles") + "/";
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			is = item.getInputStream();
			fos = new FileOutputStream(new File(realPath + filename));
			IOTools.copy(is, fos);
		} finally {
			try {
				fos.close();
				is.close();
			} catch (IOException ignored) {
			}
		}
		return filename;
	}
}
